<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

class Admini_InterfaceController extends Uuch_BaseController {

    public function init() {
        error_reporting(0);
    }

    /**
     * @return 登录
     */
    public function verifyuserAction() {
        $nikename = $this->getSafeParam("nikename");
        $password = $this->getSafeParam("password");
        $result = Application_Model_adminuser::byloginname($nikename);
        if (!$result) {
            $this->json(array("status" => 0, "message" => "用户名或密码错误！"));
            return;
        }
        if ($result->password != md5($password)) {
            $this->json(array("status" => 0, "message" => "用户名或密码错误！"));
            return;
        }
        $result->lastlogin = date("Y-m-d H:s:i");
        $result->loginnum = $result->loginnum + 1;
        $result->save();
        $this->json(array("status" => 1, "userId" => $result->Id));
        return;
    }

    /**
     * @return 根据物流单号获取包裹信息
     */
    public function getpackageinfoAction() {
        $infoArr = array();
        $userInfo = array();
        $user = "";
        $logistics = $this->getSafeParam('shipNo');
        $infoArr["intype"] = "自助包裹";
        $isCheck = true;
        $visitingItem = Application_Model_VisitingServer::getByShipNo($logistics);
        if ($visitingItem) {
            $infoArr["shipType"] = "顺丰";
            $infoArr["waresName"] = $visitingItem->waresName;
            $infoArr["waresDescribe"] = $visitingItem->waresDescribe;
            $infoArr["userid"] = $visitingItem->UserId;
            $infoArr["intype"] = "上门取件";
            $infoArr["storeid"] = $visitingItem->Id;
            $infoArr["problemNote"] = $visitingItem->problemNote;
            $user = Application_Model_User::load($visitingItem->UserId);
            $isCheck = false;
        }
        $returnGoodsItem = Application_Model_ReturnGoods::getByLogistics($logistics);
        if ($isCheck && $returnGoodsItem) {
            $problemItem = Application_Model_QualityProblem::byObjectIdObjectType($returnGoodsItem->Id, Application_Model_DomainobjectType::ObjectType_Exchange);
            $infoArr["problemNum"] = $problemItem ? $problemItem->getNum(Application_Model_QualityProblemContent::Status_Default) : 0;
            $infoArr["shipType"] = $returnGoodsItem->ReLogisticsName;
            $infoArr["name"] = $returnGoodsItem->ProductName;
            $infoArr["returnReason"] = $returnGoodsItem->ReturnReason;
            $infoArr["userid"] = $returnGoodsItem->UserId;
            $infoArr["intype"] = $returnGoodsItem->SourceName;
            $infoArr["storeid"] = $returnGoodsItem->Id;
            $infoArr["problem"] = $returnGoodsItem->Problem;
            $infoArr["exception"] = $returnGoodsItem->exception;
            $user = Application_Model_User::load($returnGoodsItem->UserId);
            $isCheck = false;
        }
        $orderItem = Application_Model_Order::getByShipNo($logistics);
        if (!$orderItem) {
            $trackItem = Application_Model_Tracking::getOneByObjectTypeOperateTypeContent(Application_Model_DomainobjectType::ObjectType_Order, Application_Model_Tracking::Type_ReissueLogistics, $logistics);
            if ($trackItem) {
                $infoArr["shipType"] = $trackItem->ShipItem->name;
                $orderItem = Application_Model_Order::load($trackItem->ObjectId);
            }
        } else {
            $infoArr["shipType"] = $orderItem->logname->name;
        }
        if ($isCheck && $orderItem) {
            $infoArr["intype"] = $orderItem->PayDescription;
            $orderPath = Application_Model_PathLevel::bySubId($orderItem->Id);
            $storeId = $orderItem->Id;
            // if ($orderPath) {
            //    //获取多条记录信息 
            //     $path = explode("/", $orderPath->Path);
            //     $subItem = Application_Model_PathLevel::byPath($path[0]);
            //     $infoArr["orderArr"] = $this->getOrderSubInfo($subItem, $storeId);
            // } else {
                //获取单条记录信息
                $problemItem = Application_Model_QualityProblem::byObjectIdObjectType($orderItem->Id, Application_Model_DomainobjectType::ObjectType_Order);
                // $infoArr["orderArr"][$storeId]["problemNum"] = $problemItem ? $problemItem->getNum(Application_Model_QualityProblemContent::Status_Default) : 0;
                // $infoArr["orderArr"][$storeId]["parentId"] = $storeId; //代购父级Id
                // $infoArr["orderArr"][$storeId]["storeid"] = $orderItem->OrderNum; //代购单号
                // $infoArr["orderArr"][$storeId]["orderId"] = $storeId; //代购父级Id
                // $infoArr["orderArr"][$storeId]["status"] = $orderItem->Status;
                // $infoArr["orderArr"][$storeId]["statusName"] = $orderItem->StatusName;
                // $infoArr["orderArr"][$storeId]["dateCreated"] = $orderItem->datePaid; //代购付款时间
                // $infoArr["orderArr"][$storeId]["orderdetail"] = $this->getOrderInfo($orderItem); //物品详情
                // $infoArr["orderArr"][$storeId]["arrProblem"] = $this->getOrderProblemInfo($storeId); //物品问题详情
                $infoArr["orderArr"][] = array(
                                            "problemNum"        => $problemItem ? $problemItem->getNum(Application_Model_QualityProblemContent::Status_Default) : 0,
                                            "parentId"          => $storeId, //代购父级Id
                                            "storeid"           => $orderItem->OrderNum, //代购单号
                                            "orderId"           => $storeId, //代购父级Id
                                            "status"            => $orderItem->Status,
                                            "statusName"        => $orderItem->StatusName,
                                            "dateCreated"       => $orderItem->datePaid, //代购付款时间
                                            "orderdetail"       => $this->getOrderInfo($orderItem), //物品详情
                                            "arrProblem"        => $this->getOrderProblemInfo($storeId), //物品问题详情
                                        );
            // }
            $user = Application_Model_User::load($orderItem->UserId);
            $isCheck = false;
        }
        $ingstore = Application_Model_ingstore::getByShipNo($logistics);
        if ($isCheck && $ingstore) {
            $problemItem = Application_Model_QualityProblem::byObjectIdObjectType($ingstore->Id, Application_Model_DomainobjectType::ObjectType_Ing);
            $infoArr["problemNum"] = $problemItem ? $problemItem->getNum(Application_Model_QualityProblemContent::Status_Default) : 0;
            $infoArr["shipType"] = $ingstore->shipType;
            $infoArr["name"] = $ingstore->name;
            $infoArr["remark"] = $ingstore->remark;
            $infoArr["userid"] = $ingstore->userid;
            $infoArr["intype"] = $ingstore->PayDescription;
            $infoArr["storeid"] = $ingstore->id;
            $user = Application_Model_User::getByUserId($ingstore->userid);
            $isCheck = false;
        }
        if ($user) {
            $userInfo["userId"] = $user->id;
            $userInfo["storeno"] = $user->storeno;
            $userInfo["email"] = $user->email;
            $userInfo["nikename"] = $user->nikename;
            $userInfo["userRemark"] = $user->remark;
            $userInfo["countstore"] = Application_Model_StoreItem::coustore($user->id);
            $userInfo["storeLocation"] = $user->byStoreLocation();
        }
        $this->json(array("infoArr" => $infoArr, "userInfo" => $userInfo));
    }

    private function getOrderSubInfo($subItem, $storeId) {
        $arrOrder = array();
        $i = 1;
        foreach ($subItem as $subVal) {
            // $parentOrderItem = Application_Model_Order::load($subVal->parentId);
            // $order = Application_Model_Order::load($subVal->SubId);
            // if ($order->Isdelete == 1) {
            //     continue;
            // }
            // if (array_key_exists($subVal->SubId, $arrOrder)) {
            //     continue;
            // }
            // $problemItem = Application_Model_QualityProblem::byObjectIdObjectType($subVal->SubId, Application_Model_DomainobjectType::ObjectType_Order);
            // $arrOrder[$order->Id]["problemNum"] = $problemItem ? $problemItem->getNum(Application_Model_QualityProblemContent::Status_Default) : 0;
            // $arrOrder[$order->Id]["isSel"] = 0; //选择入库的代购
            // if ($storeId == $order->Id) {
            //     $arrOrder[$order->Id]["isSel"] = 1;
            // }
            // $arrOrder[$order->Id]["parentId"] = $subVal->parentId; //代购父级Id
            // $arrOrder[$order->Id]["storeid"] = $parentOrderItem->OrderNum . "($i)"; //代购单号
            // $arrOrder[$order->Id]["orderId"] = $order->Id;
            // $arrOrder[$order->Id]["status"] = $order->Status;
            // $arrOrder[$order->Id]["statusName"] = $order->StatusName; 
           
            // $problemItem = Application_Model_QualityProblem::byObjectIdObjectType($order->Id,Application_Model_DomainobjectType::ObjectType_Order);
            // $contentArr = $problemItem?$problemItem->getContentTrack():"";
            // $arrOrder[$order->Id]["problemContent"] = $this->getProblemContentStr($contentArr); //问题原因
            // // $arrOrder[$order->Id]["problemContent"] = $order->problemContent; //问题原因
            // $arrOrder[$order->Id]["dateCreated"] = $order->datePaid; //代购付款时间
            // $arrOrder[$order->Id]["orderdetails"] = $this->getOrderInfo($order); //物品详情
            // $arrOrder[$order->Id]["arrProblem"] = $this->getOrderProblemInfo($order->Id); //物品问题详情

            $parentOrderItem = Application_Model_Order::load($subVal->parentId);
            $order = Application_Model_Order::load($subVal->SubId);
            if ($order->Isdelete == 1) {
                continue;
            }
            if (array_key_exists($subVal->SubId, $arrOrder)) {
                continue;
            }
            $problemItem = Application_Model_QualityProblem::byObjectIdObjectType($subVal->SubId, Application_Model_DomainobjectType::ObjectType_Order);
            $arrOrder[$i-1]["problemNum"] = $problemItem ? $problemItem->getNum(Application_Model_QualityProblemContent::Status_Default) : 0;
            $arrOrder[$i-1]["isSel"] = 0; //选择入库的代购
            if ($storeId == $order->Id) {
                $arrOrder[$i-1]["isSel"] = 1;
            }
            $arrOrder[$i-1]["parentId"] = $subVal->parentId; //代购父级Id
            $arrOrder[$i-1]["storeid"] = $parentOrderItem->OrderNum . "($i)"; //代购单号
            $arrOrder[$i-1]["orderId"] = $order->Id;
            $arrOrder[$i-1]["status"] = $order->Status;
            $arrOrder[$i-1]["statusName"] = $order->StatusName; 

            $problemItem = Application_Model_QualityProblem::byObjectIdObjectType($order->Id,Application_Model_DomainobjectType::ObjectType_Order);
            $contentArr = $problemItem?$problemItem->getContentTrack():"";
            $arrOrder[$i-1]["problemContent"] = $this->getProblemContentStr($contentArr); //问题原因
            // $arrOrder[$i-1]["problemContent"] = $order->problemContent; //问题原因
            $arrOrder[$i-1]["dateCreated"] = $order->datePaid; //代购付款时间
            $arrOrder[$i-1]["orderdetails"] = $this->getOrderInfo($order); //物品详情
            $arrOrder[$i-1]["arrProblem"] = $this->getOrderProblemInfo($order->Id); //物品问题详情
            $i++;
        }
        return $arrOrder;
    }

    private function getOrderInfo($order) {
        $orderdetail = array();
        $orderItem = $order->shipdetail;
        foreach ($orderItem as $key1 => $ordervalue) {
            $problemItem = Application_Model_QualityProblem::byObjectIdObjectType($ordervalue->Id, Application_Model_DomainobjectType::ObjectType_OrderItem);
            $orderdetail[$key1]["problemNum"] = $problemItem ? $problemItem->getNum(Application_Model_QualityProblemContent::Status_Default) : 0;
            $orderdetail[$key1]["id"] = $ordervalue->id; //商品id
            $orderdetail[$key1]["productName"] = $ordervalue->productName; //商品名称
            $orderdetail[$key1]["price"] = $ordervalue->price; //商品单价
            $orderdetail[$key1]["quantity"] = $ordervalue->quantity; //商品数量
            $orderdetail[$key1]["status"] = $ordervalue->status; //商品状态
            $orderdetail[$key1]["comment"] = $ordervalue->comment; //商品备注
            $orderdetail[$key1]["description"] = $ordervalue->description; //悠奇备注
            
            $problemItem = Application_Model_QualityProblem::byObjectIdObjectType($ordervalue->id,Application_Model_DomainobjectType::ObjectType_OrderItem);
            $contentArr = $problemItem?$problemItem->getContentTrack():"";
            $orderdetail[$key1]["problemContent"] = $this->getProblemContentStr($contentArr); //问题原因
            // $orderdetail[$key1]["problemContent"] = $ordervalue->problemContent; //问题描述
            $orderdetail[$key1]["ckPass"] = $ordervalue->CkPass; //物品状态
            $productd = $ordervalue->byproductd;
            $orderdetail[$key1]["url"] = $productd->url; //淘宝地址
            $orderdetail[$key1]["tgurl"] = Application_Model_OrderItem::GetTopUrl($productd, $ordervalue); //推广地址
            $orderdetail[$key1]["remoteImage"] = $productd->remoteImage; //图片地址			
            //$orderdetail[$key1]["PropertyAlias"] = iconv_strlen($productd->PropertyAlias) >= 50 ? mb_substr($productd->PropertyAlias, 0, 50, 'utf-8') . '...' : $productd->PropertyAlias; //商品款式
			$propertyAliasString = Application_Model_Product::parsePropertyAlias($productd->PropertyAlias);
			$orderdetail[$key1]["PropertyAlias"] = iconv_strlen($propertyAliasString) >= 50 ? mb_substr($propertyAliasString, 0, 50, 'utf-8') . '...' : $propertyAliasString; //商品款式
        }
        return $orderdetail;
    }

    private function getOrderProblemInfo($orderId) {
        $arrProblem = array();
        $problemItem = Application_Model_problem::byissue($orderId, Application_Model_problem::TYPE_ORDER);
        foreach ($problemItem as $key => $pbVal) {
            $arrProblem[$key]["issueetype"] = $pbVal->Issuetype;
            $arrProblem[$key]["content"] = htmlspecialchars($pbVal->Content);
            $arrProblem[$key]["dateCreated"] = $pbVal->DateCreated;
        }
        return $arrProblem;
    }

    /**
     * @return 根据仓库号获取用户信息
     */
    public function getuserinfoAction() {
        $storeNo = $this->getSafeParam('storeno');
        $firstWord = substr($storeNo, 0, 1);
        $user = NULL;
        $type = Application_Model_StoreItem::SOURCE_SELF;
        $addtion = array();
        $storeid = null;
        $arrOrder = array();
        if ($firstWord == 'F') {//代购订单
            //$storeNo = 'P'.substr($storeNo, 1);
            //$type = Application_Model_StoreItem::SOURCE_AGENT_BUY;
        } else if ($firstWord == 'D') {
            $type = Application_Model_StoreItem::SOURCE_AGENT_BUY;
            $storeId = substr($storeNo, 1);
            $order = Application_Model_Order::load($storeId);
            if (!$order) {
                $this->json(0);
                return;
            }
            $user = Application_Model_User::load($order->UserId);
            // $orderPath = Application_Model_PathLevel::bySubId($storeId);
            // if ($orderPath) {
            //     $path = explode("/", $orderPath->Path);
            //     $subItem = Application_Model_PathLevel::byPath($path[0]);
            //     $arrOrder = $this->getOrderSubInfo($subItem, $storeId);
            // } else {
                // $problemItem = Application_Model_QualityProblem::byObjectIdObjectType($storeId, Application_Model_DomainobjectType::ObjectType_Order);
                // $arrOrder[$storeId]["parentId"] = $order->Id; //代购父级Id
                // $arrOrder[$storeId]["storeid"] = $order->OrderNum; //代购单号
                // $arrOrder[$storeId]["status"] = $order->Status;
                // $arrOrder[$storeId]["statusName"] = $order->StatusName;
                
                // $problemItem = Application_Model_QualityProblem::byObjectIdObjectType($storeId,Application_Model_DomainobjectType::ObjectType_Order);
                // $contentArr = $problemItem?$problemItem->getContentTrack():"";
                // $arrOrder[$storeId]["problemContent"] = $this->getProblemContentStr($contentArr); //问题原因
                // // $arrOrder[$storeId]["problemContent"] = $order->problemContent; //问题原因
                // $arrOrder[$storeId]["dateCreated"] = $order->datePaid; //代购付款时间
                // $arrOrder[$storeId]["problemNum"] = $problemItem ? $problemItem->getNum(Application_Model_QualityProblemContent::Status_Default) : 0;
                // $arrOrder[$storeId]["orderdetails"] = $this->getOrderInfo($order); //物品详情
                // $arrOrder[$storeId]["arrProblem"] = $this->getOrderProblemInfo($order->Id); //物品问题详情
                $problemItem = Application_Model_QualityProblem::byObjectIdObjectType($storeId,Application_Model_DomainobjectType::ObjectType_Order);
                $contentArr = $problemItem?$problemItem->getContentTrack():"";
                $arrOrder[] = array(
                                "parentId"          => $order->Id, //代购父级Id
                                "storeid"           => $order->OrderNum, //代购单号
                                "status"            => $order->Status,
                                "statusName"        => $order->StatusName,
                                "problemContent"    => $this->getProblemContentStr($contentArr), //问题原因
                                "dateCreated"       => $order->datePaid, //代购付款时间
                                "problemNum"        => $problemItem ? $problemItem->getNum(Application_Model_QualityProblemContent::Status_Default) : 0,
                                "orderdetails"      => $this->getOrderInfo($order), //物品详情
                                "arrProblem"        => $this->getOrderProblemInfo($order->Id), //物品问题详情
                            );
            // }
        } else if (preg_match('/^\d+$/', $storeNo)) {//上门取件
            $no = strrev($storeNo);
            $visiting = Application_Model_VisitingServer::load('1' . $no);
            if ($visiting) {
                $problemItem = Application_Model_QualityProblem::byObjectIdObjectType($visiting->Id, Application_Model_DomainobjectType::ObjectType_Visiting);
                $addtion["problemNum"] = $problemItem ? $problemItem->getNum(Application_Model_QualityProblemContent::Status_Default) : 0;
                $user = Application_Model_User::load($visiting->UserId);
                $type = Application_Model_StoreItem::SOURCE_VISITING;
                $storeid = $visiting->Id;
                $addtion['name'] = $visiting->WaresName;
                $addtion['description'] = $visiting->WaresDescribe;
                if ($visiting->IsWay == 1 and $visiting->WayId != "") {
                    $type = Application_Model_StoreItem::SOURCE_VISITINGWAY;
                    $problemItem = Application_Model_QualityProblem::byObjectIdObjectType($visiting->Id, Application_Model_DomainobjectType::ObjectType_VisitingWay);
                    $addtion["problemNum"] = $problemItem ? $problemItem->getNum(Application_Model_QualityProblemContent::Status_Default) : 0;
                }
            }
        }
        if (!$user) {
            $user = Application_Model_User::getByStoreNo($storeNo);
        }
        if ($user == null) {
            $this->json(0);
            return;
        }
        $storeLocation = $user->byStoreLocation();
        $countstore = Application_Model_StoreItem::coustore($user->id);
        $this->json(array('userid' => $user->Id, 'type' => $type, 'email' => $user->Email, 'nikeName' => $user->Nikename, 'storeno' => $user->Storeno, 'countstore' => $countstore, 'dq' => $user->byip, 'storeLocation' => $storeLocation, "userRemark" => $user->remark, 'addtion' => $addtion,
            "storeid" => $storeid, "arrOrder" => $arrOrder));
    }

    /**
     * @return 保存包裹信息
     */
    public function savepackageinfoAction() {
        $logistics = $this->getSafeParam('logistics');
        $logisticsName = $this->getSafeParam('logisticName');
        $storeno = $this->getSafeParam("storeno");
        $storeId = $this->getSafeParam('storeId');
        $adminId = $this->getSafeParam("adminId");
        $userid = $this->getSafeParam('userid');
        $operator = Application_Model_adminuser::load($adminId);
        if (!$operator) {
            $this->json(array("status" => 0, "message" => "登录信息过期，请重新登录！"));
            return;
        }
        if (!$this->getSafeParam('issplitbox') && !$this->AnalysisOrder($storeId)) {
            $this->json(array("status" => 0, "message" => "该代购订单的状态错误，无法入库。请跟上面代购人员沟通！"));
            return;
        }
        $userItem = Application_Model_User::load($userid);
        if (!$userItem) {
            $this->json(array("status" => 0, "message" => "该用户不存在，请重新输入！"));
            return;
        }
        $barcode = Application_Model_StoreItem::createBarCode();

        $itemType = "";
        if (is_array($this->_getParam('itemType'))) {
            foreach ($this->_getParam('itemType') as $type) {
                $itemType = $itemType | intval($type);
            }
        } else {
            $itemType = $this->_getParam('itemType');
        }
        $itemType = ($itemType == "" || $itemType == NULL) ? 0 : $itemType;
        $item = new Application_Model_StoreItem();
        $item->productName = $this->getSafeParam('productName');
        $item->storeId = $storeId;
        $item->dateInStore = $this->now();
		$item->dateOver = date('Y-m-d H:i:s', strtotime('+6 month'));
        $item->quantity = 1;
        $item->state = Application_Model_StoreItem::STATUS_Bind;
        $item->logisticsName = $logisticsName;
        $item->logistics = $logistics;
        $item->orderNo = $item->Logistics;
        $item->userid = $userid;
        $item->weight = 0;
        $item->length = 0;
        $item->width = 0;
        $item->height = 0;
        $item->createdate = $this->now();
        $item->isPack = $this->getSafeParam('isPack');
        $item->cnShipFee = $this->getSafeParam('cnShipFee');
        $item->bignessType = 0;
        $item->volumeWeight = 0;
        $item->CanVacuum = $this->getSafeParam('canVacuum');
        $item->isEmbargo = $this->getSafeParam('isEmbargo');
        $item->embargoReason = $this->getSafeParam("embargoReason");
        $item->barcode = $barcode;
        $item->Image = $this->getSafeParam('image');
        $item->Image = str_replace("http://old.uuch.com", "", $item->Image);
        $item->itemType = $itemType;
        $item->remark = $this->getSafeParam('remark');
        $item->intype = $this->getSafeParam('intype');
        $item->operateName = $operator->Nikename;
        $item->interior = Application_Model_StoreItem::Interior_HoldItem;
        $item->isdelete = 0;
        $item->IsProblem = 0;
        $itemCount = Application_Model_StoreItem::getCountByUserId($item->Userid);
        if ($itemCount == 0) {
            $accountItem = Application_Model_UserAccount::addAccount($item->Userid);
            $accountItem->TaskExchangeScore(Application_Model_Task::TASK_INSTORE);
        }
        try {
            $item->save();
        } catch (Exception $e) {
            $this->json(array("status" => 0, "message" => "同一时间有别的商品入库，造成仓库条码冲突，请重新入库！"));
            return;
        }
        $img = $this->getSafeParam('image');
        $arrImg = explode(",", $img);
        $defaultImg = "";
        foreach ($arrImg as $key => $imgVal) {
            if ($imgVal != "") {
                $item->addImg($imgVal, Application_Model_StoreImg::Status_Default);
                $defaultImg = $imgVal;
            }
        }
        $item->Image = $defaultImg;
        $item->save();
        Application_Model_Operate::addOperate(0, null, $item->barcode, "包裹".$item->barcode."入单", $item->userid);
        $this->AnalysisOrderIng($item,$storeno, $logistics, $logisticsName);
        $this->json(array("status"=>1,"storeId"=>$item->Id,"barcode"=>$item->barcode));
        return ;
    }

    /**
     * @return 保存包裹全部信息
     */
    public function saveallinfoAction() {
        $logistics = $this->getSafeParam('logistics');
        $logisticsName = $this->getSafeParam('logisticName');
        $storeno = $this->getSafeParam("storeno");
        $storeId = $this->getSafeParam('storeId');
        $adminId = $this->getSafeParam("adminId");
        $userid = $this->getSafeParam('userid');
        $weight = $this->getSafeParam("weight");
        $operator = Application_Model_adminuser::load($adminId);
        if (!$operator) {
            $this->json(array("status" => 0, "message" => "登录信息过期，请重新登录！"));
            return;
        }
        if (!$this->getSafeParam('issplitbox') && !$this->AnalysisOrder($storeId)) {
            $this->json(array("status" => 0, "message" => "该代购订单的状态错误，无法入库。请跟上面代购人员沟通！"));
            return;
        }
        $userItem = Application_Model_User::load($userid);
        if (!$userItem) {
            $this->json(array("status" => 0, "message" => "该用户不存在，请重新输入！"));
            return;
        }
        if ($weight == "" || $weight == 0) {
            $this->json(array("status" => 0, "message" => "重量不能为空或为零！"));
            return;
        }
//        $barcode = Application_Model_StoreItem::createBarCode();
        $barcode = $this->getSafeParam("barcode");
        $itemType = $this->getSafeParam('itemType');
        $item = new Application_Model_StoreItem();
        $item->productName = $this->getSafeParam('productName');
        $item->storeId = $storeId;
        $item->dateInStore = $this->now();
		$item->dateOver = date('Y-m-d H:i:s', strtotime('+6 month'));
        $item->quantity = 1;
        $item->state = Application_Model_StoreItem::STATUS_InStored;
        $item->logisticsName = $logisticsName;
        $item->logistics = $logistics;
        $item->orderNo = $item->Logistics;
        $item->userid = $userid;
        $item->weight = $weight * 1000;
        $item->length = $this->getSafeParam('length');
        $item->width = $this->getSafeParam('width');
        $item->height = $this->getSafeParam('height');
        $item->createdate = $this->now();
        $item->isPack = $this->getSafeParam('isPack');
        $item->cnShipFee = $this->getSafeParam('cnShipFee');
        $item->bignessType = 0;
        $item->volumeWeight = $this->getSafeParam("volumeWeight") ? ($this->getSafeParam("volumeWeight") * 1000) : ($item->length * $item->width * $item->height / 5);
        $item->CanVacuum = $this->getSafeParam('canVacuum');
        $item->isEmbargo = $this->getSafeParam('isEmbargo');
        $item->embargoReason = $this->getSafeParam("embargoReason");
        $item->barcode = $barcode;
        $item->Image = $this->getSafeParam('image');
        $item->Image = str_replace("http://old.uuch.com", "", $item->Image);
        $item->itemType = $itemType;
        $item->remark = $this->getSafeParam('remark');
        $item->intype = $this->getSafeParam('intype');
        $item->operateName = $operator->Nikename;
        $item->interior = Application_Model_StoreItem::Interior_HoldItem;
        $item->isdelete = 0;
        $item->IsProblem = 0;
//        var_dump($item);exit;
        $itemCount = Application_Model_StoreItem::getCountByUserId($item->Userid);
        if ($itemCount == 0) {
            $accountItem = Application_Model_UserAccount::addAccount($item->Userid);
            $accountItem->TaskExchangeScore(Application_Model_Task::TASK_INSTORE);
        }
           
        try {
            $item->save();
        } catch (Exception $e) {
            $this->json(array("status" => 0, "message" => "同一时间有别的商品入库，造成仓库条码冲突，请重新入库！"));
            return;
        }
        //双十一入库加积分
        if(date("Y-m-d", time()) < '2016-11-12'){
            $usermodel = Application_Model_UserAccount::getByUserId($userid);
            $usermodel->hdscore +=1; 
            $usermodel->save();
        }
        $Kinfo = Application_Model_User::getByStoreno($storeno);
        if(preg_match("/^[0-9a-zA-Z]+@(([0-9a-zA-Z]+)[.])+[a-z]{2,4}$/i",$Kinfo->email)){
            $receive = array('email' => $Kinfo->email, 'name' => $Kinfo->email);
            $link = 'http://www.uuch.com/storehouse/personal/';
            $name = $Kinfo->nikename;
            $this->sendUserRkMail($receive, $link, $name, $logistics);
        }          
        $img = $this->getSafeParam('image');
        $arrImg = explode(",", $img);
        $defaultImg = "";
        foreach ($arrImg as $key => $imgVal) {
            if ($imgVal != "") {
                $item->addImg($imgVal, Application_Model_StoreImg::Status_Default);
                $defaultImg = $imgVal;
            }
        }
        $item->Image = $defaultImg;
        $item->save();
        Application_Model_Operate::addOperate(0, null, $item->barcode, "包裹".$item->barcode."入单", $item->userid);
        $this->AnalysisOrderIng($item,$storeno, $logistics, $logisticsName);
        $this->json(array("status"=>1,"message"=>"132165"));
        return ;
    }

   /**
     * 入库邮件提醒
     */
    public function sendUserRkMail($receive, $link, $name, $bill) {
        $title = "包裹入库通知";
        $body = "尊敬的悠奇用户：" . $name . "您好！
                    
                感谢您选择悠奇网的服务

                您的国内包裹（" . $bill . "）已由快悌公司派送至悠奇公司，我们已对您的包裹拍照、称重并已上传信息至您的

                个人云仓库，如您需要查看包裹信息及状态请点击下面的链接查看。

                $link

                如果您点击此链接后发现它可能已损坏，请复制此链接并将其粘贴到新的浏览器窗口中。

                感谢您使用 uuch！

                uuch悠奇网敬上

                请不要回复此邮件。如果您要与UUCH小组联系，请登录您的帐户，点击任何页面顶部的“帮助”，然后点击“帮助中心”底部的“与我们联系”。
                ";

        return Uuch_Mail2::SendMail($title, $body, $receive);
    }

    private function AnalysisOrder($storeId) {
        $order = Application_Model_Order::load($storeId);
        if (!$order) { //不是代购
            return true;
        }
        //入库代购状态错误
        if ($order->status == Application_Model_Order::STATUS_SELLER_SENDED || $order->status == Application_Model_Order::STATUS_SUBSCRIBE || $order->status == Application_Model_Order::STATUS_OUTTIME_INSTORE || $order->status == Application_Model_Order::STATUS_OUTTIME_FIN) {
            return true;
        }
        return false;
    }

    private function AnalysisOrderIng($item, $storeno, $logistics, $logisticsName) {
        $operator = $item->operateName;
        $firstWord = substr($storeno, 0, 1);
        $shipItem = Application_Model_shipType::getByName($logisticsName);
        $shipId = 181; //其他
        if ($shipItem) {
            $shipId = $shipItem->Id;
        }
        $orderItem = Application_Model_Order::getByShipNo($logistics);
        if (!$orderItem) {
            $trackItem = Application_Model_Tracking::getOneByObjectTypeOperateTypeContent(Application_Model_DomainobjectType::ObjectType_Order, Application_Model_Tracking::Type_ReissueLogistics, $logistics);
            if ($trackItem) {
                $orderItem = Application_Model_Order::load($trackItem->ObjectId);
                $item->productName = "代购订单" . $orderItem->OrderNum . "物品部分入库";
                $item->save();
                $orderItem->rechangeStatus = Application_Model_Order::ReChange_Complete;
                $orderItem->save();
            }
        }
        if ($orderItem) {
            $orderItem->status = Application_Model_Order::STATUS_INSTORE;
            $orderItem->dateInStore = date('Y-m-d H:i:s');
            $orderItem->dateConfrim = date("Y-m-d H:i:s");
            $orderItem->ActivityConsumeExchangeScore();
            $orderItem->save();
            $isCk = false;
            foreach ($orderItem->getItems() as $val) {
                if ($val->CkPass == Application_Model_DomainobjectType::CK_Problem) {
                    $isCk = true;
                }
            }
            if ($orderItem->CkPass == Application_Model_DomainobjectType::CK_Problem) {
                $isCk = true;
            }
            if ($isCk) {
                $item->productName = "代购订单" . $orderItem->OrderNum . "物品部分入库";
                $item->IsProblem = Application_Model_DomainobjectType::CK_Problem;
                $item->save();
//                Application_Model_Mail::addMail( "您收到一个质检异常的包裹",1,$item->userid,"您的代购订单".$orderItem->OrderNum."入库出现质检异常，<a href='/member/orderdetail/id/".$orderItem->Id."' target='_block'>点击查看详情！</a>");
            }
        }
        if ($firstWord == 'D') {
            $storeId = substr($storeno, 1);
            $order = Application_Model_Order::load($storeId);
            if ($order->scheme == Application_Model_Order::Scheme_Change || $order->scheme == Application_Model_Order::Scheme_Reissue) {
                Application_Model_Tracking::addTrack(Application_Model_DomainobjectType::ObjectType_Order, $storeId, $operator, $logistics, Application_Model_Tracking::User_None, Application_Model_Tracking::Type_ReissueLogistics, date("Y-m-d H:i:s"), $shipId);
                $orderItem->rechangeStatus = Application_Model_Order::ReChange_Complete;
                $orderItem->save();
            }
            $order->logistics = $shipId;
            $order->logisticsNo = $logistics;
            $order->dateInStore = date('Y-m-d H:i:s');
            $order->dateConfrim = date("Y-m-d H:i:s");
            $order->status = Application_Model_Order::STATUS_INSTORE;
            $order->ActivityConsumeExchangeScore();
            $order->save();
            $isCk = false;
            foreach ($order->getItems() as $val) {
                if ($val->CkPass == Application_Model_DomainobjectType::CK_Problem) {
                    $isCk = true;
                }
            }
            if ($order->CkPass == Application_Model_DomainobjectType::CK_Problem) {
                $isCk = true;
            }
            if ($isCk) {
                $item->productName = "代购订单" . $orderItem->OrderNum . "物品部分入库";
                $item->IsProblem = Application_Model_DomainobjectType::CK_Problem;
                $item->save();
//                Application_Model_Mail::addMail( "您收到一个质检异常的包裹",1,$item->userid,"您的代购订单".$orderItem->OrderNum."入库出现质检异常，<a href='/member/orderdetail/id/".$orderItem->Id."' target='_block'>点击查看详情！</a>");
            }
        }
        //预报包裹
        $ingstoreItem = Application_Model_ingstore::getByShipNo($logistics);
        if ($ingstoreItem) {
            $ingstoreItem->state = '1';
            $ingstoreItem->save();
            if ($ingstoreItem->CkPass == Application_Model_DomainobjectType::CK_Problem) {
                $item->IsProblem = Application_Model_DomainobjectType::CK_Problem;
                $item->save();
//                Application_Model_Mail::addMail( "您收到一个质检异常的包裹",1,$item->userid,"您的预报包裹入库出现质检异常，<a href='/member/forecastdetail?id=".$ingstoreItem->Id."' target='_block'>点击查看详情！</a>");
            }
        }
        //换货包裹
        $returnGoods = Application_Model_ReturnGoods::getByLogistics($logistics);
        if ($returnGoods) {
            $returnGoods->status = Application_Model_ReturnGoods::STATUS_Receipt;
            $returnGoods->save();
            $returnGoods->addBillLog(Application_Model_ReturnGoods::STATUS_Receipt);
            Application_Model_Operate::addOperate(0, null, $returnGoods->productName, "退换货" . $returnGoods->productName . " 仓库已收件", $returnGoods->UserId);
            if($returnGoods->CkPass == Application_Model_DomainobjectType::CK_Problem){
                $item->IsProblem = Application_Model_DomainobjectType::CK_Problem;
                $item->save();
//                Application_Model_Email::sendMail($item->userid, $item->userinfo->email, "您收到一个质检异常的包裹", "您的预报包裹入库出现质检异常，<a href='/member/forecastdetail?id=".$ingstoreItem->Id."' target='_block'>点击查看详情！</a>");
            }
        }
        //上门取件
        if (preg_match('/^\d+$/', $storeno)) {
            $no = strrev($storeno);
            $visiting = Application_Model_VisitingServer::load('1' . $no);
            if ($visiting) {
                $visiting->VisitingInStore($item->logistics);
            }
        }
        if ($item->intype == "上门取件") {
            $visitingItem = Application_Model_VisitingServer::getByShipNo($logistics);
            if ($visitingItem) {
                $visitingItem->VisitingInStore($item->logistics);
            }
        }
        if($item->IsProblem == Application_Model_DomainobjectType::CK_Problem){
            Application_Model_Operate::addOperate(0, null, $item->barcode, "设置入库包裹 " . $item->barcode . " 为问题包裹", $item->userid);
        }
        return true;
    }

    /**
     * @return 通过仓库条码获取用户信息
     */
    public function getpackageuserinfoAction() {
        $barcode = $this->getSafeParam("barcode");
        $storeItem = Application_Model_StoreItem::surebybarcode($barcode);
        if (!$storeItem) {
            $this->json(array("status" => 0, "message" => "包裹不存在，请确认条码的正确"));
            return;
        }
        $userItem = Application_Model_User::load($storeItem->Userid);
        if (!$userItem) {
            $this->json(array("status" => 0, "message" => "该包裹所属用户不存在，请联系管理人员。"));
            return;
        }
        $userArr["storeId"] = $storeItem->Id;
        $userArr["nikename"] = $userItem->Nikename;
        $userArr["email"] = $userItem->Email;
        $userArr["storeno"] = $userItem->Storeno;
        $userArr["storeLocation"] = $userItem->byStoreLocation();
        $this->json(array("status" => 1, "userArr" => $userArr));
    }

    /**
     * @return 保存仓库物品的重量体积
     */
    public function saveweightvolumeAction() {
        $barcode = $this->getSafeParam("barcode");
        $storeItem = Application_Model_StoreItem::surebybarcode($barcode);
        if (!$storeItem) {
            $this->json(array("status" => 0, "message" => "包裹不存在，请重新输入仓库条码"));
            return;
        }
        $weight = $this->getSafeParam("weight");
//        var_dump($weight);exit;
        if ($weight == "" || $weight == 0) {
            $this->json(array("status" => 0, "message" => "包裹重量不能为空或为零"));
            return;
        }
        $length = $this->getSafeParam('length') ? $this->getSafeParam('length') : 0;
        $width = $this->getSafeParam('width') ? $this->getSafeParam('width') : 0;
        $height = $this->getSafeParam('height') ? $this->getSafeParam('height') : 0;
        $volume = ($length * $width * $height) / 5000;
        $volumeWeight = $this->getSafeParam('volumeWeight');
        $volumeWeight = $volumeWeight ? $volumeWeight : ($volume == 0 ? $weight : $volume);
        $storeItem->weight = $weight * 1000;
        $storeItem->length = $length;
        $storeItem->width = $width;
        $storeItem->height = $height;
        $storeItem->volumeWeight = $volumeWeight * 1000;
        $storeItem->save();
        $this->json(array("status" => 1));
        return;
    }

    /**
     * @return 仓库物品上传图片的准备工作
     */
    public function verifypackagestatusAction() {
        $storeId = $this->getSafeParam("storeId");
        $storeItem = Application_Model_StoreItem::load($storeId);
        if (!$storeItem) {
            $this->json(array("status" => 0, "message" => "该包裹不存在，请检查"));
            return;
        }
        if ($storeItem->weight == 0 || $storeItem->volumeWeight == 0) {
            $this->json(array("status" => 0, "message" => "该包裹重量体积还未更新"));
            return;
        }
        $imgUrl = "";
        foreach ($storeItem->getImgs() as $imgVal) {
            $imgUrl .= $imgVal->imgurl;
        }
        $this->json(array("status" => 1, "imgUrl" => $imgUrl));
        return;
    }

    /**
     * @return 更新商品状态
     */
    public function updatepackagestatusAction() {
        $storeId = $this->getSafeParam("storeId");
        $storeItem = Application_Model_StoreItem::load($storeId);
        if (!$storeItem) {
            $this->json(array("status" => 0, "message" => "该包裹不存在，请检查！"));
            return;
        }
        if ($storeItem->weight == 0 || $storeItem->volumeWeight == 0) {
            $this->json(array("status" => 0, "message" => "该包裹重量体积还未更新！"));
            return;
        }
//        if($storeItem->state != Application_Model_StoreItem::STATUS_Bind){
//            $this->json(array("status"=>0,"message"=>"该包裹状态错误，请检查！"));
//            return ;
//        }
        foreach ($storeItem->getImgs() as $imgVal) {
            $imgVal->status = Application_Model_StoreImg::Status_Succeed;
            $imgVal->save();
        }
        $storeItem->state = Application_Model_StoreItem::STATUS_InStored;
        $storeItem->save();
        $this->json(array("status" => 1));
        return;
    }

    /**
     * @return 保存问题详情
     */
    public function saveproblemAction() {
        $storeid = $this->getSafeParam("storeid");
        $examineType = $this->getSafeParam("examineType");
        $problemContent = $this->getSafeParam("problemContent");
        $isAbnormal = $this->getSafeParam("isAbnormal");
        $orderProblemImg = $this->getSafeParam("orderProblemImg");
        $userId = $this->getSafeParam("userId");
        $userItem = Application_Model_adminuser::load($userId);
//        if(!$userItem) {
//            $this->json(array("status"=>0,"message"=>"登录信息过期，请重新登录！"));
//            return ;
//        }
        if ($problemContent == "") {
            $this->json(array("status" => 0, "message" => "问题内容不能为空"));
            return;
        }
        $objectType = "";
        $objectItem = false;
        if ($examineType == "ingProblem") {
            $objectType = Application_Model_DomainobjectType::ObjectType_Ing;
            $objectItem = Application_Model_ingstore::load($storeid);
        } else if ($examineType == "rerProblem") {
            $objectType = Application_Model_DomainobjectType::ObjectType_Exchange;
            $objectItem = Application_Model_ReturnGoods::load($storeid);
        } else if ($examineType == "orderProblem") {
            $objectType = Application_Model_DomainobjectType::ObjectType_Order;
            $objectItem = Application_Model_Order::load($storeid);
            $objectItem->isAbnormal = $isAbnormal;
        } else if ($examineType == "orderItemProblem") {
            $objectType = Application_Model_DomainobjectType::ObjectType_OrderItem;
            $objectItem = Application_Model_OrderItem::load($storeid);
            if ($isAbnormal == Application_Model_Order::Abnormal_Less) {
                $objectItem->status = Application_Model_OrderItem::Status_Less;
            } else if ($isAbnormal == Application_Model_Order::Abnormal_Error) {
                $objectItem->status = Application_Model_OrderItem::Status_Error;
            }
            $orderItem = Application_Model_Order::load($objectItem->OrderId);
            $orderItem->isAbnormal = $isAbnormal;
            $orderItem->save();
        } else if ($examineType == "visitingProblem") {
            $objectType = Application_Model_DomainobjectType::ObjectType_Visiting;
            $objectItem = Application_Model_VisitingServer::load($storeid);
        } else if ($examineType == "visitingWayProblem") {
            $objectType = Application_Model_DomainobjectType::ObjectType_VisitingWay;
            $objectItem = Application_Model_VisitingServer::load($storeid);
        }
        if ($objectType == "" || !$objectItem) {
            $this->json(array("status" => 0, "message" => "设置问题的包裹不存在，请重新操作！"));
            return;
        }
        $operator = $userItem->nikename;
        $problemItem = Application_Model_QualityProblem::byObjectIdObjectType($storeid, $objectType);
        if ($problemItem) {
            $problemId = $problemItem->Id;
        } else {
            $problemId = Application_Model_QualityProblem::addQualtiyProblem($objectType, $storeid);
        }
        $contentProblemId = Application_Model_QualityProblemContent::addQualityProblemContent($problemId, $problemContent, date("Y-m-d H:i:s"), $operator, Application_Model_QualityProblemContent::Status_Default);

//        $img = $this->getSafeParam('image');
        $arrImg = explode(",", $orderProblemImg);
        foreach ($arrImg as $key => $imgVal) {
            Application_Model_QualityProblemImg::addQualityProblemImg($contentProblemId, str_replace("http://old.uuch.com", "", $imgVal));
        }
        $objectItem->CkPass = Application_Model_DomainobjectType::CK_Problem;
        $objectItem->save();
        $this->json(array("status" => 1, "message" => ""));
        return;
    }

    /**
     * @return 根据物品Id与物品类型获取问题详情
     */
    public function getproblemAction() {
        $storeid = $this->getSafeParam("storeid");
        $examineType = $this->getSafeParam("examineType");
        $objectType = "";
        $objectItem = false;
        if ($examineType == "ingProblem") {
            $objectType = Application_Model_DomainobjectType::ObjectType_Ing;
            $objectItem = Application_Model_ingstore::load($storeid);
        } else if ($examineType == "rerProblem") {
            $objectType = Application_Model_DomainobjectType::ObjectType_Exchange;
            $objectItem = Application_Model_ReturnGoods::load($storeid);
        } else if ($examineType == "orderProblem") {
            $objectType = Application_Model_DomainobjectType::ObjectType_Order;
            $objectItem = Application_Model_Order::load($storeid);
        } else if ($examineType == "orderItemProblem") {
            $objectType = Application_Model_DomainobjectType::ObjectType_OrderItem;
            $objectItem = Application_Model_OrderItem::load($storeid);
        } else if ($examineType == "visitingProblem") {
            $objectType = Application_Model_DomainobjectType::ObjectType_Visiting;
            $objectItem = Application_Model_VisitingServer::load($storeid);
        } else if ($examineType == "visitingWayProblem") {
            $objectType = Application_Model_DomainobjectType::ObjectType_VisitingWay;
            $objectItem = Application_Model_VisitingServer::load($storeid);
        }
        if ($objectType == "" || !$objectItem) {
            $this->json(array("status" => 0, "该问题包裹不存在，请重新操作！"));
            return;
        }
        $problemItem = Application_Model_QualityProblem::byObjectIdObjectType($storeid, $objectType);
        $contentArr = $problemItem ? $problemItem->getContent() : "";
        $problemNum = $problemItem ? $problemItem->getNum(Application_Model_QualityProblemContent::Status_Default) : 0;
        $this->json(array("status" => 1, "contentArr" => $contentArr, "problemNum" => $problemNum));
        return;
    }

    /**
     * @return 根据问题Id删除问题
     */
    public function delproblemAction() {
        $contentId = $this->getSafeParam("contentId");
        $contentItem = Application_Model_QualityProblemContent::load($contentId);
        if (!$contentItem) {
            $this->json(array("status" => 0, "message" => "该问题不存在！"));
            return;
        }
        $problemId = $contentItem->ProblemId;
        $contentItem->delete();
        $problemNum = Application_Model_QualityProblemContent::getNum($problemId, "");
        if ($problemNum == 0) {
            $problemItem = Application_Model_QualityProblem::load($problemId);
            $problemItem->delProblem();
            $problemItem->delete();
        }
        $this->json(array("status" => 1));
        return;
    }

    public function getproblemimgAction() {
        $contentId = $this->getSafeParam("problemId");
        $contentItem = Application_Model_QualityProblemContent::load($contentId);
        if (!$contentItem) {
            $this->json(array("status" => 0, "message" => "该问题不存在！"));
            return;
        }
        $imgUrl = "";
        foreach ($contentItem->getImgs() as $imgVal) {
            $imgUrl .= $imgVal->imgUrl;
        }
        $this->json(array("status" => 1, "imgUrl" => $imgUrl));
        return;
    }

    /**
     * @return 更新问题的状态
     */
    public function updateproblemstatusAction() {
        $contentId = $this->getSafeParam("contentId");
        $contentItem = Application_Model_QualityProblemContent::load($contentId);
        if (!$contentItem) {
            $this->json(array("status" => 0, "message" => "该问题不存在！"));
            return;
        }
//        if($contentItem->status == Application_Model_QualityProblemContent::Status_Bind){
        $contentItem->status = Application_Model_QualityProblemContent::Status_Default;
        $contentItem->save();
//        }
        $this->json(array("status" => 1));
        return;
    }

    public function getshipinfoAction() {
        $words = array();
        for ($i = 0; $i < 26; $i++) {
            $name = chr(65 + $i);
            $shipItem = Application_Model_shipType::getByWord($name);
            foreach ($shipItem as $shipVal) {
                $words[$name][] = $shipVal->Name;
            }
        }
        $this->json(array("ship" => $words));
        return;
    }

    public function printwayAction() {
        $type = $this->getSafeParam("type");
        $wayId = $this->getSafeParam("wayId");
        $wayItem = Application_Model_wayBillItem::load($wayId);
        if (!$wayItem) {
            $this->json(array("status" => 0, "message" => "国际运单不存在！"));
            return;
        }
        $inventoryArr = array();
        $siteArr = array();
        $invoiceArr = array();
        $shipArr = array();
        if ($type == 0 || $type == 1) {
            $inventoryArr["wayinfo"] = $this->WayInfo($wayItem);
            foreach ($wayItem->getItems() as $itemVal) {
                $storeItem = Application_Model_StoreItem::load($itemVal->storeItemId);
                $inventoryArr["storeinfo"][$itemVal->Id]["barcode"] = $storeItem->barcode;
                $inventoryArr["storeinfo"][$itemVal->Id]["image"] = $storeItem->image;
                $inventoryArr["storeinfo"][$itemVal->Id]["productName"] = $storeItem->productName;
                $inventoryArr["storeinfo"][$itemVal->Id]["ItemTypeName"] = $storeItem->ItemTypeName;
                $inventoryArr["storeinfo"][$itemVal->Id]["weight"] = $storeItem->weight / 1000;
                $inventoryArr["storeinfo"][$itemVal->Id]["volume"] = $storeItem->volumeWeight ? $storeItem->volumeWeight / 1000 : "无";
                $inventoryArr["storeinfo"][$itemVal->Id]["locationNo"] = $storeItem->locationNo ? $storeItem->locationNo : "无";
            }
        }
        if ($type == 0 || $type == 2) {
            $affirmAgent = Application_Model_WayLog::getByWayIdInteriorType($wayItem->id, Application_Model_WayLog::Type_BillAffirmAgent);
            $siteArr["wayinfo"]["agentId"] = $affirmAgent ? $affirmAgent->description : $wayItem->agentId;
            $siteArr["wayinfo"]["word"] = $wayItem->UserCity->word;
            $siteArr["wayinfo"]["shipto"] = $wayItem->consignee;
            $siteArr["wayinfo"]["tel"] = $wayItem->conTel;
            $siteArr["wayinfo"]["address"] = $wayItem->conAdd;
            $siteArr["wayinfo"]["postalcode"] = $wayItem->conPostCode;
            $siteArr["wayinfo"]["state"] = $wayItem->UserCity->ename . '(' . $wayItem->UserCity->name . ')';
            $siteArr["wayinfo"]["billno"] = $wayItem->billNo;
            $siteArr["wayinfo"]["storeno"] = $wayItem->user->storeno;
            if ($wayItem->AgentId == Application_Model_AgentCompany::Agent_4px) {
                $siteArr["wayinfo"]["info4px"] = Uuch_4pxAPI::byAgentNo($wayItem->agentNo);
            }
        }
        if ($type == 0 || $type == 2 || $type == 3 || $type == 4) {
            $invoiceall = Application_Model_invoice::bybillNo($wayItem->billNo);
            if (!$invoiceall) {
                $this->json(array("status" => 0, "message" => "国际运单还没有添加发票！"));
                return;
            }
            $invoiceArr = $this->InvoiceInfo($invoiceall);
        }
        $this->json(array("status" => 1, "inventoryArr" => $inventoryArr, "siteArr" => $siteArr, "invoiceArr" => $invoiceArr, "shipArr" => $shipArr));
        return;
    }

    protected function WayInfo($wayItem) {
        $reArr["billNo"] = $wayItem->billNo;
        $reArr["storeno"] = $wayItem->user->storeno;
        $reArr["userId"] = $wayItem->user->id;
        $reArr["nikename"] = $wayItem->user->nikename;
        $reArr["state"] = $wayItem->UserCity->name . '(' . $wayItem->UserCity->ename . ')';
        $reArr["datePait"] = $wayItem->datePaid;
        $reArr["shipName"] = $wayItem->ExpressBy->name;
        $reArr["isNoLogo"] = $wayItem->isNoLogo == 1 ? "是" : "否";
        $reArr["isNoSkin"] = $wayItem->isNoSkin == 1 ? "是" : "否";
        $reArr["isVacuum"] = $wayItem->IsCompress ? "是(费用:+" . $wayItem->getFeeByType(Application_Model_FeeType::VacuumSeviceFee) . "元)" : "否";
        $reArr["isWooden"] = $wayItem->isWooden ? "是(费用:+" . $wayItem->getFeeByType(Application_Model_FeeType::WoodenFee) . "元)" : "否";
        $reArr["isFragileFee"] = $wayItem->getFeeByType(Application_Model_FeeType::FragileFee) > 0 ? "是(费用:+" . $wayItem->getFeeByType(Application_Model_FeeType::FragileFee) . "元)" : "否";
        $reArr["locationName"] = $wayItem->locationName;
        $volumeWeight = $wayItem->getWeightByType(Application_Model_WeightType::EstimateVolume);
        $productWeight = $wayItem->getWeightByType(Application_Model_WeightType::ProductWeight);
        $bagWeight = $wayItem->getWeightByType(Application_Model_WeightType::BagWeight);
        if ($wayItem->ExpressBy->isVolume == 1) {
            $reArr["payWeight"] = ($volumeWeight > ($productWeight + $bagWeight)) ? ($volumeWeight / 1000) . "kg(按预估包裹体积)" : (($productWeight + $bagWeight) / 1000) . "kg(按预估包裹重量)";
        } else {
            $reArr["payWeight"] = (($productWeight + $bagWeight) / 1000) . "kg(按预估包裹重量)";
        }
        $reArr["payMoney"] = $wayItem->getFeeByType(Application_Model_FeeType::EstimateSum);
        $reArr["reprotMoany"] = $wayItem->getFeeByType(Application_Model_FeeType::ReprotValue) > 0 ? '$' . $wayItem->getFeeByType(Application_Model_FeeType::ReprotValue) . ' USD' : '未填写';
        $reArr["premiumMoney"] = $wayItem->getFeeByType(Application_Model_FeeType::RatePremiumFee) > 0 ? $wayItem->getFeeByType(Application_Model_FeeType::PremiumValue) . '元(保费:' . $wayItem->getFeeByType(Application_Model_FeeType::RatePremiumFee) . '元)' : "未投保";
        $reArr["address"] = $wayItem->consignee . "," . $wayItem->conTel . "," . $wayItem->conAdd . "," . $wayItem->conPostCode;
        $reArr["remark"] = $wayItem->remark;
        $reArr["interiorRemark"] = $wayItem->interiorRemark;
        $remarks = Application_Model_Remark::getObjectRemark($wayItem->id);
        $remarksString = '';
        $i = 1;
        foreach($remarks as $_remark){
            $remarksString .= $_remark->operator . '在 ' . $_remark->createdAt . ' 留言：' . $_remark->content;
            if($i != count($remarks)){
                $remarksString .= "\n";
            }
            $i ++;
        }
        if($remarksString){
            if($reArr["interiorRemark"]){
                $reArr["interiorRemark"] .= "\n" . $remarksString;
            }else{
                $reArr["interiorRemark"] = $remarksString;
            }
            
        }
        $reArr["userRemark"] = $wayItem->user->remark;
        return $reArr;
    }

    protected function InvoiceInfo($invoiceall) {
        $invoiceArr = array();
        $wayItem = Application_Model_wayBillItem::bybillNo($invoiceall->billNo);
        $splitWay = Application_Model_WaySplit::byWayId($wayItem->Id);
        $shipItem = Application_Model_WayLog::getByWayIdInteriorType($wayItem->Id, Application_Model_WayLog::Type_ShipType);
        $channelLog = Application_Model_WayLog::getByWayIdInteriorType($wayItem->Id, Application_Model_WayLog::Type_BillAffirmChannel);
        $invoiceArr["invoice"]["shipName"] = $shipItem ? $shipItem->description : ($channelLog ? $channelLog->DescriptionByChannel->name : ($wayItem->channelname ? $wayItem->channelname->name : ""));
        $invoiceArr["invoice"]["date"] = $invoiceall->orderdate;
        $invoiceArr["invoice"]["invoiceNo"] = $invoiceall->invoiceno;
        $invoiceArr["invoice"]["num"] = $splitWay ? count($splitWay) : 1;
        $invoiceArr["invoice"]["formAddress"] = "No.3 Langshan 2nd Street,Area of Hi-Tech Industrial Zone Nanshan District, SHENZHEN GUANGDONG CHINA";
        $invoiceArr["invoice"]["formTel"] = "0755-88605979";
        $invoiceArr["invoice"]["formContact"] = "UUCH";
        $invoiceArr["invoice"]["formState"] = "China(中国)";
        $invoiceArr["invoice"]["toAddress"] = $invoiceall->address;
        $invoiceArr["invoice"]["toZipcode"] = $invoiceall->zipcode;
        $invoiceArr["invoice"]["toTel"] = $invoiceall->tel;
        $invoiceArr["invoice"]["toContact"] = $invoiceall->attn;
        $invoiceArr["invoice"]["toState"] = $invoiceall->country;
        $invoiceArr["invoice"]["reason"] = $invoiceall->reason;
        $invoiceArr["invoice"]["total"] = $invoiceall->total;
        $invoiceArr["invoice"]["billNo"] = $invoiceall->billNo;
        foreach ($invoiceall->getDetails() as $detailVal) {
            $invoiceArr["detail"][$detailVal->id]["pkgs"] = $detailVal->pkgs > 0 ? $detailVal->pkgs : "";
            $invoiceArr["detail"][$detailVal->id]["description"] = $detailVal->description;
            $invoiceArr["detail"][$detailVal->id]["hscode"] = $detailVal->hscode;
            $invoiceArr["detail"][$detailVal->id]["num"] = $detailVal->num;
            $invoiceArr["detail"][$detailVal->id]["price"] = $detailVal->price;
            $invoiceArr["detail"][$detailVal->id]["total"] = $detailVal->total;
        }
        return $invoiceArr;
    }

    protected function getProblemContentStr($contentArr){
        $str = '';
        if(!empty($contentArr)){
            foreach ($contentArr as $key => $content) {
                $str .= $content['content'] . ';';
            }
            if(!empty($str)){
                $str = substr($str,0,strlen($str)-1); 
            }
        }
        return $str;
    }

}
